import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_play_android/common/user.dart';
import 'package:flutter_play_android/net/dio_manager.dart';
import 'package:flutter_play_android/utils/sp_util.dart';
import 'package:flutter_play_android/utils/toast_util.dart';

class WanAndroidErrorInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    String errorMsg = DioManager.handleError(err);
    ToastUtil.show(msg: errorMsg);
    super.onError(err, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    var data = response.data;
    if (data is String) data = json.decode(data);
    if(data is Map){
      int errorCode = data['errorCode'] ?? -1;
      String errorMsg = data['errorMsg'] ?? '请求失败[$errorCode]';
      if(errorCode == 0){
      super.onResponse(response, handler);
      }else if(errorCode == -1001){
        User().clearUserInfo();
        dio.clear();
        SPUtil.clear();
        goLogin();
        handler.reject(
            DioError(requestOptions: response.requestOptions, error: errorMsg));
      } else {
        ToastUtil.show(msg: errorMsg);
        handler.reject(
            DioError(requestOptions: response.requestOptions, error: errorMsg));
      }
    }
  }

  void goLogin() {
    /// 在拿不到context的地方通过navigatorKey进行路由跳转：
    /// https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app
    // navigatorKey.currentState?.pushNamed(RouterName.login);
  }
}
